"""
多任务TCP服务器示例
1.循环等待客户端连接
2.为每个连接创建一个新线程
3.处理客户端请求
"""
import socket
import threading
def handle_client(client_socket, client_address):
    print(f"客户端{client_address}已连接")
    while True:
        bytes_data = client_socket.recv(2048)  # 接收数据
        if bytes_data:
            msg = bytes_data.decode("GBK")
            print(f"客户端{client_address}说：{msg}")
        else:
            print(f"客户端{client_address}已断开连接")
            client_socket.close()
            break

if __name__ == '__main__':
    # 创建socketTCP服务器
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定IP和端口号
    server_socket.bind(("", 8888))
    # 开始监听客户端连接,被动监听
    server_socket.listen(128)
    print("服务器已启动")
    while True:
        client_socket, client_address = server_socket.accept()
        # 有新的客户端接入
        print("新的客户端接入")
        t1 = threading.Thread(target=handle_client, args=(client_socket, client_address))
        t1.daemon = True
        t1.start()